<template>
    <el-tree
        ref="menu"
        class="menu"
        node-key="id"
        :data="menuList"
        :props="menuProps"
        draggable
        default-expand-all
        highlight-current
        @check="checkNode"
        :expand-on-click-node="false"
        @node-click="menuClick"
        @node-drop="nodeDrop"
        :default-expanded-keys="defaultExpandIds"
        @node-expand="handleNodeExpand"
        @node-collapse="handleNodeCollapse"
    >
        <template #default="{ node, data }">
            <span class="custom-tree-node">
                <span class="label-wrap">
                    <el-icon><component :is="data.icon" /></el-icon>
                    <span class="label">
                        {{ node.label }}
                    </span>
                </span>

                <span class="do">
                    <el-button-group>
                        <el-button icon="el-icon-plus" size="small" @click.stop="addMenu(node, data)"></el-button>
                        <el-button icon="el-icon-delete" size="small" @click.stop="delMenu(node, data)" :disabled="data.children != null"></el-button>
                    </el-button-group>
                </span>
            </span>
        </template>
    </el-tree>
    <menuDetailDrawer ref="drawer" v-if="show" @closed="save = false" @success="handleSuccess"></menuDetailDrawer>
</template>

<script>
import menuDetailDrawer from './menu-detail.vue';
export default {
    emits: ['update:modelValue'],
    components: {
        menuDetailDrawer
    },
    props: {
        modelValue: { type: Array, default: () => [] }
    },
    watch: {
        modelValue: {
            handler(newVal) {
                this.menuList = JSON.parse(JSON.stringify(newVal));
            },
            immediate: true,
            deep: true
        }
    },
    data() {
        return {
            defaultExpandIds: [],
            menuProps: {
                label: (data) => {
                    return data.label;
                }
            },
            menuList: [],
            show: false
        };
    },
    methods: {
        //树点击
        menuClick(data, node) {
            this.show = true;
            this.$nextTick(() => {
                this.$refs.drawer.setData(node, data, 'edit');
            });
            // this.nodeId = data.id
            // var pid = node.level == 1 ? undefined : node.parent.data.id
            // this.$refs.save.setData(data.id, pid)
            // this.$refs.main.$el.scrollTop = 0
            // this.showEdit = true
        },
        //树拖拽
        async nodeDrop() {
            // console.log(draggingNode, dropNode, dropType)
            // var res = await this.$API.system.menu.dragMenu.put(dropType, draggingNode.data.id, dropNode.data.id)
            // if (res.code == 200) {
            this.$message.success('操作成功');
            //this.$message(`拖拽对象：${draggingNode.data.label}+${draggingNode.data.id}, 释放对象：${dropNode.data.label}+${dropNode.data.id}, 释放对象的位置：${dropType}`)
            // }
        },
        //选择节点
        checkNode() {
            this.showDelete = false;
            var CheckedNodes = this.$refs.menu.getCheckedNodes();
            if (CheckedNodes.length > 0) {
                this.showDelete = true;
            }
        },
        //增加菜单
        async addMenu(node, item) {
            this.show = true;
            this.$nextTick(() => {
                this.$refs.drawer.setData(node, item, 'add');
            });
        },
        //删除菜单
        async delMenu(node, data) {
            this.$confirm(`确认要删除已选择的菜单吗？`, '提示', {
                type: 'warning',
                confirmButtonText: '删除',
                confirmButtonClass: 'el-button--danger'
            })
                .then(async () => {
                    let res = await this.$API.app.menu.delMenu.delete(data.id);
                    if (res.code == 200) {
                        this.$refs.menu.remove(node);
                        this.$message.success('操作成功');
                    } else {
                        this.this.$message.error('操作失败');
                    }
                    this.$emit('update:modelValue', this.menuList);
                })
                .catch(() => {});
        },
        async handleSuccess(formData) {
            formData.appId = this.$route.query.appId;
            if (formData.id != null) {
                let res = await this.$API.app.menu.updateMenuData.update(formData);
                if (res.code == 200) {
                    // console.log(formData);
                    // const i = this.menuList.find((item) => {
                    //     return item.id === formData.menuParent;
                    // });
                    // if (i && Array.isArray(i.children)) {
                    //     i.children.forEach((item) => {
                    //         if (item.id === formData.id) {
                    //             item.label = formData.menuName;
                    //             item.menuUrl = formData.menuUrl;
                    //             item.menuAction = formData.menuAction;
                    //             item.icon = formData.menuIcon;
                    //             return;
                    //         }
                    //     });
                    // }
                    this.$message.success('修改成功');
                } else {
                    this.$message.error('修改失败');
                }
            } else {
                // const i = this.menuList.find((item) => {
                //     if (item.id == formData.menuParent) {
                //         return item;
                //     }
                // });
                // if (typeof i.children == 'undefined') {
                //     i.children = [];
                // }
                console.log(formData, 'formData');
                let res = await this.$API.app.menu.addMenu.post(formData);
                // if (formData.id == null) {
                if (res.code == 200) {
                    // i.children.push({
                    //     id: res.data,
                    //     label: formData.menuName,
                    //     menuUrl: formData.menuUrl
                    // });
                    this.$message.success('新增成功');
                } else {
                    this.$message.error('新增失败');
                }
                // }
            }
            this.$emit('update:modelValue', this.menuList);
        },
        // 树节点展开
        handleNodeExpand(data) {
            // 保存当前展开的节点
            let flag = false;
            this.defaultExpandIds.some((item) => {
                if (item === data.id) {
                    // 判断当前节点是否存在， 存在不做处理
                    flag = true;
                    return true;
                }
            });
            if (!flag) {
                // 不存在则存到数组里
                this.defaultExpandIds.push(data.id);
            }
        },
        // 树节点关闭
        handleNodeCollapse(data) {
            // 删除当前关闭的节点
            this.defaultExpandIds.some((item, i) => {
                if (item === data.id) {
                    this.defaultExpandIds.splice(i, 1);
                }
            });
            this.removeChildrenIds(data); // 这里主要针对多级树状结构，当关闭父节点时，递归删除父节点下的所有子节点
        },
        // 删除树子节点
        removeChildrenIds(data) {
            const ts = this;
            if (data.children) {
                data.children.forEach(function (item) {
                    const index = ts.defaultExpandIds.indexOf(item.id);
                    if (index > 0) {
                        ts.defaultExpandIds.splice(index, 1);
                    }
                    ts.removeChildrenIds(item);
                });
            }
        }
    }
};
</script>

<style lang="scss" scoped>
.menu {
    width: 100%;
    height: 100%;
    // background-color: transparent;
    padding-top: 10px;
}
.menu:deep(.el-tree-node__expand-icon) {
    padding-left: 10px;
}
.menu:deep(.el-tree-node__label) {
    display: flex;
    flex: 1;
    height: 100%;
}
.custom-tree-node {
    display: flex;
    flex: 1;
    align-items: center;
    justify-content: space-between;
    font-size: 14px;
    height: 100%;
    padding-right: 10px;
}
.custom-tree-node .label-wrap {
    display: flex;
    align-items: center;
    height: 100%;
}

.custom-tree-node .label-wrap .el-icon svg {
    transform: translateY(1px);
}
.custom-tree-node .label {
    display: flex;
    align-items: center;
    height: 100%;
    margin-left: 5px;
}
.custom-tree-node .label .el-tag {
    margin-left: 5px;
}
.custom-tree-node .do {
    display: none;
}
.custom-tree-node .do i {
    margin-left: 5px;
    color: #999;
}
.custom-tree-node .do i:hover {
    color: #333;
}

.custom-tree-node:hover .do {
    display: inline-block;
}
</style>
